package com.yanjr.modules.sys.service.impl;

import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yanjr.common.persistence.Page;
import com.yanjr.common.utils.CacheUtils;
import com.yanjr.common.utils.IdGen;
import com.yanjr.common.utils.StringUtils;
import com.yanjr.modules.sys.dao.DictDao;
import com.yanjr.modules.sys.entity.Dict;
import com.yanjr.modules.sys.service.DictService;
import com.yanjr.modules.sys.utils.DictUtils;
import com.yanjr.modules.sys.utils.UserUtils;

@Service("dictService")
@Transactional(readOnly = true)
public class DictServiceImpl implements DictService {

	@Autowired
	private DictDao dictDao;
	
	@Override
	public Dict get(String id) {
		return dictDao.get(id);
	}

	@Override
	public Page<Dict> find(Page<Dict> page, Dict dict) {
		StringBuffer sql = new StringBuffer("select * from sys_dict where 1=1 ");
		if(StringUtils.isNotEmpty(dict.getType())) {
			sql.append(" and type='" + dict.getType() + "'");
		}
		if(StringUtils.isNotEmpty(dict.getDescription())) {
			sql.append(" and description like %" + dict.getDescription().trim() + "% ");
		}
		
		return dictDao.findPage(page, sql.toString());
	}

	@Override
	public List<String> findTypeList() {
		return dictDao.findTypeList();
	}

	@Override
	@Transactional(readOnly = false)
	public void save(Dict dict) {
		if(StringUtils.isEmpty(dict.getId())) {
			dict.setId(IdGen.uuid());
			dict.setCreateBy(UserUtils.getUser().getId());
			dict.setUpdateBy(UserUtils.getUser().getId());
			dict.setUpdateDate(new Date());
			dictDao.save(dict);
		} else {
			dict.setUpdateBy(UserUtils.getUser().getId());
			dict.setUpdateDate(new Date());
			dictDao.update(dict);
		}
		CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
	}

	@Override
	@Transactional(readOnly = false)
	public void delete(String id) {
		dictDao.deleteById(id);
		CacheUtils.remove(DictUtils.CACHE_DICT_MAP);
	}

}
